﻿//------------------------------------------------------------
// shaco Framework
// Copyright © 2017-2021 chang.liu All rights reserved.
// Feedback: 449612236@qq.com
//------------------------------------------------------------

namespace shaco
{
    /// <summary>
    /// 自定义excel数据加载类
    /// </summary>
    public class ExcelDataLoaderDefault : shaco.Base.IExcelDataLoader
    {
        virtual public shaco.Base.ExcelData Load(string path)
        {
            shaco.Base.ExcelData retValue = null;
            var request = shaco.GameHelper.res.Load<UnityEngine.Object>(path);
            if (null != request)
            {
                retValue = LoadExcelDataFromResource(request);
            }
            return retValue;
        }

        virtual public void LoadAsync(string path, System.Action<shaco.Base.ExcelData> callbackEnd, System.Action<float> callbackProgress = null)
        {
            if (null == callbackEnd)
            {
                Log.Error("ExcelHelper LoadAsync error: callback function is invalid");
                return;
            }

            var request = shaco.GameHelper.res.LoadAsync<UnityEngine.Object>(path);
            OnLoadAsync(request, callbackEnd, callbackProgress);
        }

        virtual public void UnLoad(shaco.Base.IResourceHandle request)
        {
            request.Release();
        }

        protected void OnLoadAsync(shaco.Base.IResourceHandle request, System.Action<shaco.Base.ExcelData> callbackEnd, System.Action<float> callbackProgress = null)
        {
            shaco.Base.ExcelData retValue = null;
            request.OnCompleted((obj) =>
            {
                if (null != obj)
                {
                    retValue = LoadExcelDataFromResource(request);

                    if (null != retValue && null != callbackEnd)
                        callbackEnd(retValue);
                }
                else
                {
                    if (null != callbackEnd)
                        callbackEnd(null);
                }
            });

            if (null != callbackProgress)
                shaco.WaitFor.Run(() => !request.isDone, () => callbackProgress(request.progress));
        }

        protected shaco.Base.ExcelData LoadExcelDataFromResource(shaco.Base.IResourceHandle request)
        {
            shaco.Base.ExcelData retValue = null;

            //如果是新版asset文件，则从asset文件来初始化excelData数据
            var path = request.ToString();
            var readTmp = request.assetObject as UnityEngine.Object;
            if (null == readTmp)
                throw new System.Exception("LoadExcelDataFromResource request.AssetObject not 'UnityEngine.Object' type");
            if (readTmp.GetType() == typeof(shaco.ExcelDefaultAsset))
            {
                retValue = new shaco.Base.ExcelData();
                retValue.InitWithRowDatas(((shaco.ExcelDefaultAsset)readTmp).datas, path);
            }
            else
            {
                //从csv文件初始化数据
                var readBytes = readTmp.ToBytes();
                if (!readBytes.IsNullOrEmpty())
                {
                    retValue = new shaco.Base.ExcelData();
                    retValue.InitWithBinary(readBytes, path);
                }
                else
                {
                    Log.Error("ExcelDataLoaderDefault LoadExcelDataFromResource erorr: no data, path=" + path);
                }
            }
            retValue.resourceRequest = request;
            return retValue;
        }

        // /// <summary>
        // /// 获取当前环境文件读取路径
        // /// </summary>
        // private string GetCurrentEnviromentExcelPath(string path)
        // {
        //     var retValue = new System.Text.StringBuilder();
        //     var runtimeLoadFileExtension = string.Empty;
        //     var runtimeLoadFileType = shaco.Base.GameHelper.excelSetting.runtimeLoadFileType;

        //     //全局设定路径
        //     if (!string.IsNullOrEmpty(_prefixPath))
        //     {
        //         retValue.Append(_prefixPath);
        //         if (!_prefixPath.EndsWith(System.IO.Path.DirectorySeparatorChar))
        //             retValue.Append(System.IO.Path.DirectorySeparatorChar);
        //     }

        //     //读取文件夹路径
        //     var customResourcePath = shaco.Base.GameHelper.excelSetting.GetCustomLoadPath(path);
        //     if (!string.IsNullOrEmpty(customResourcePath))
        //     {
        //         retValue.Append(customResourcePath);
        //         retValue.Append(System.IO.Path.DirectorySeparatorChar);
        //     }
        //     else
        //     {
        //         Log.Warning("ExcelHelper+Unity GetCurrentEnviromentExcelPath warning: custom load path is empty, excel path=" + path);
        //     }

        //     //后缀名
        //     switch (runtimeLoadFileType)
        //     {
        //         case shaco.Base.ExcelData.RuntimeLoadFileType.CSV: runtimeLoadFileExtension = shaco.Base.ExcelDefine.EXTENSION_TXT; break;
        //         case shaco.Base.ExcelData.RuntimeLoadFileType.UnityAsset: runtimeLoadFileExtension = shaco.Base.ExcelDefine.EXTENSION_ASSET; break;
        //         default: Log.Error("ExcelDataSerializable SerializableAsCSharpScript error: unsupport load type=" + runtimeLoadFileType); break;
        //     }

        //     var fileName = System.IO.Path.GetFileName(path);
        //     fileName = System.IO.Path.ChangeExtension(fileName, runtimeLoadFileExtension);
        //     retValue.Append(fileName);
        //     return retValue.ToString();
        // }
    }
}